package com.kkb.proxy.dynamic;

import java.lang.reflect.Method;

import com.kkb.proxy.statix.AOP;
import com.kkb.service.NoInterfaceService;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

/**
 * Cglib 动态代理工厂
 *
 * @author ztranscript 2021/8/28 14:58
 **/
public class CglibProxyFactory {

    /**
     * 目标对象
     */
    private NoInterfaceService service;
    /**
     * 切面
     */
    private AOP aop;

    public CglibProxyFactory(NoInterfaceService service, AOP aop) {
        this.service = service;
        this.aop = aop;
    }

    /**
     * 获取JDK动态代理实例
     *
     * @return jdkProxy
     */
    public Object getProxyInstance() {
        return Enhancer.create(service.getClass(), new MethodHandler());
    }

    private class MethodHandler implements MethodInterceptor {
        /**
         * 拦截被代理类方法,增强其功能
         *
         * @param o           拦截类的子类
         * @param method      拦截方法
         * @param objects     方法入数
         * @param methodProxy 拦截方法的代理
         * @return 方法返回值
         * @throws Throwable 异常
         */
        @Override
        public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
            try {
                aop.before();
                // 调用被代理类实现功能
                Object o1 = methodProxy.invokeSuper(o, objects);
                aop.after();
                return o1;
            } catch (Exception e) {
                aop.exception();
                throw e;
            } finally {
                aop.myFinally();
            }
        }
    }

}
